//
//  HMPictureView.swift
//  webo
//
//  Created by apple on 2016/11/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
private let cellid = "HMPictureCellid"

class HMPictureView: UICollectionView {
    var pictureInfos: [HMPictuerInfo]? {
        didSet{
        self.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
//        self.register(UINib.init(nibName: "HMPictureCell", bundle: nil), forSupplementaryViewOfKind: <#T##String#>, withReuseIdentifier: <#T##String#>)
        
        
        self.register(UINib.init(nibName: "HMPictureCell", bundle: nil), forCellWithReuseIdentifier: cellid)
     self.dataSource = self
        self.delegate = self
    }
    
}
//
extension HMPictureView: UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return pictureInfos?.count ?? 0
    }
//    func dequeueReusableCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell {
//        let item = dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! HMPictureCell
//        item.pictureInfo = pictureInfos?[indexPath.item]
//     return item
//    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item = dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! HMPictureCell
                item.pictureInfo = pictureInfos?[indexPath.item]
             return item
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //1. 实例化图片浏览器对象
        let borwser = SDPhotoBrowser()
        borwser.sourceImagesContainerView = self
        borwser.currentImageIndex = indexPath.item
        borwser.imageCount = pictureInfos?.count ?? 0
        //设置代理
        borwser.delegate = self
        //显示图片浏览器
        borwser.show()
    }

}



extension HMPictureView: SDPhotoBrowserDelegate{
    //返回高质量图片的url对象
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let picinfo = self.pictureInfos![index]
        let url = URL(string: picinfo.imgbmiddle ?? "")
        
        return url
    }
    //返回一个占位的图片
     func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        //获取cell
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.cellForItem(at: indexPath ) as? HMPictureCell
        return cell?.iconImage.image
    }

}


